﻿Imports System.Text.RegularExpressions

''' <summary>
''' 複数形書式変換器
''' </summary>
''' <remarks></remarks>
Public NotInheritable Class PluralFormatter

    Private Sub New()
    End Sub

    Private Shared _replaceDictionary As Dictionary(Of String, String)

    ''' <summary>
    ''' 複数形変換辞書
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared ReadOnly Property ReplaceDictionary As Dictionary(Of String, String)
        Get
            If _replaceDictionary Is Nothing Then
                '簡易的な単語複数形変換
                _replaceDictionary = New Dictionary(Of String, String)
                _replaceDictionary.Add("(?<char>[^aiueo])y$", "${char}ies")
                _replaceDictionary.Add("(?<last>(s$|ss$|sh$|ch$|o$|x$))", "${last}es")
                _replaceDictionary.Add("fe$|f$", "ves")
            End If
            Return _replaceDictionary
        End Get
    End Property

    ''' <summary>
    ''' 複数形書式にします
    ''' </summary>
    ''' <param name="modelType"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function ToPlural(modelType As Type) As String
        If modelType Is Nothing Then Throw New ArgumentNullException("modelType")
        If modelType.IsNRelation Then Return modelType.Name

        Dim s = PluralFormatter.ToPlural(modelType.Name)
        Return s
    End Function

    ''' <summary>
    ''' 複数形書式にします
    ''' </summary>
    ''' <param name="name"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function ToPlural(name As String) As String
        '辞書変換
        For Each keyName As String In (From el In PluralFormatter.ReplaceDictionary.Reverse Select el.Key)
            If Regex.IsMatch(name, keyName) Then
                name = Regex.Replace(name, keyName, ReplaceDictionary(keyName))
                Return name
            End If
        Next

        '該当しない場合は末尾に「s」追加
        Return name & "s"
    End Function

End Class
